package com.example.sanguogameserver.config;

import com.example.sanguogameserver.consts.ResponseCode;
import com.example.sanguogameserver.exception.NotFoundException;
import com.example.sanguogameserver.response.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;
import java.util.List;
import org.springframework.validation.BindException;

@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(value = NotFoundException.class)
    @ResponseBody
    public Result notFoundException(NotFoundException e) {
        log.error("找不到资源", e);
        Result result = new Result();
        result.setCode(404);
        result.setMessage("找不到资源");
        return result;
    }


    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseBody
    public Result authException(AuthenticationException e) {
        log.error("token错误", e);
        ResponseCode responseCode = ResponseCode.valueOf(e.getMessage());
        Result fail = Result.responseCode(responseCode);
        return fail;
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(BindException e) {
        log.error("参数绑定异常", e);
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        return Result.fail(getErrMsgByFieldError(fieldErrors));
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        log.error("系统异常", e);
        Result fail = Result.fail(e.toString());
        fail.setCode(ResponseCode.businessException.code);
        return fail;
    }


    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public Result exceptionHandler(IllegalArgumentException e) {
        log.error("业务异常", e);
        return Result.fail(e.getMessage());

    }

    private String getErrMsgByFieldError(List<FieldError> fieldErrors) {
        String errFormat = "column: %s message: %s ";
        StringBuilder result = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            result.append(String.format(errFormat, fieldError.getField(), fieldError.getDefaultMessage()));
        }
        return result.toString();
    }
}